package com.micangcaihang.micang.mvp.task.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.micangcaihang.common.base.fragment.BaseFragment;
import com.micangcaihang.common.utils.Properties;
import com.micangcaihang.common.utils.StringUtils;
import com.micangcaihang.common.utils.TimeUtils;
import com.micangcaihang.common.utils.ToastUtils;
import com.micangcaihang.micang.R;
import com.micangcaihang.micang.databinding.FragmentTaskTuftInfoBinding;
import com.micangcaihang.micang.entity.PickerEntity;
import com.micangcaihang.micang.entity.TuftInfoEntity;
import com.micangcaihang.micang.http.request.TaskTuftRequest;
import com.micangcaihang.micang.mvp.task.contract.TaskTuftInfoContract;
import com.micangcaihang.micang.mvp.task.presenter.TaskTuftInfoPresenter;
import com.micangcaihang.micang.view.PickerViewHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * <pre>
 *     author : Fandy
 *     e-mail : fandayongfly@gmail.com
 *     time   : 2017/07/24
 *     update : 2017/07/24
 *     desc   : 房产信息
 *     version: 1.0
 * </pre>
 */

public class TaskTuftInfoFragment extends BaseFragment<TaskTuftInfoPresenter, FragmentTaskTuftInfoBinding> implements TaskTuftInfoContract.View {
    private TaskTuftRequest mRequest = new TaskTuftRequest();
    private TaskTuftRequest mOldRequest = new TaskTuftRequest();
    private String id;
    private List<PickerEntity> mRingRdDirectionData;
    private List<PickerEntity> mCirclePositionData;
    private boolean isNetSuccess;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        id = getArguments().getString("id", "");
    }

    public static TaskTuftInfoFragment newInstance(String id) {
        Bundle args = new Bundle();
        TaskTuftInfoFragment fragment = new TaskTuftInfoFragment();
        args.putString("id", id);
        fragment.setArguments(args);
        return fragment;
    }


    /**
     * 获取资源文件布局
     *
     * @return 资源布局文件layout
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_task_tuft_info;
    }

    @Override
    public void initPresenter() {
        super.initPresenter();
        mPresenter.setId(id);
    }

    @Override
    protected void initData() {
        super.initData();
        mRequest.setId(id);
        mOldRequest.setId(id);
        mRingRdDirectionData = new ArrayList<>();
        mCirclePositionData = new ArrayList<>();
    }

    /**
     * 初始化按钮监听
     */
    @Override
    protected void initListener() {
        mViewBinding.setClickHandler(new ClickHandler());
    }

    @Override
    public void returnTuftInfoData(TuftInfoEntity entity) {
        isNetSuccess = true;
        String[] excludsArray = new String[]{"choose_list", "id"};
        try {
            Properties.copyPropertiesExclude(entity, mRequest, excludsArray);
            Properties.copyPropertiesExclude(entity, mOldRequest, excludsArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //房屋户型
        StringBuffer amount = new StringBuffer();
        if (!StringUtils.isEmpty(mRequest.getRoom_amount())) {
            amount.append(mRequest.getRoom_amount()).append("室");
        }
        if (!StringUtils.isEmpty(mRequest.getHall_amount())) {
            amount.append(mRequest.getHall_amount()).append("厅");
        }
        if (!StringUtils.isEmpty(mRequest.getToilet_amount())) {
            amount.append(mRequest.getToilet_amount()).append("卫");
        }
        if (!StringUtils.isEmpty(mRequest.getKitchen_amount())) {
            amount.append(mRequest.getKitchen_amount()).append("厨");
        }
        if (!StringUtils.isEmpty(amount.toString())) {
            mViewBinding.tvAmount.setText(amount.toString());
        }
        //产权人
        mViewBinding.etPropertyOwner.setText(entity.getProperty_owner());
        //房屋坐落
        mViewBinding.etHouseLocated.setText(entity.getHouse_located());
        //小区名称
        mViewBinding.etCommunityName.setText(entity.getCommunity_name());
        //房产证号码
        mViewBinding.etCertificateNumber.setText(entity.getCertificate_number());
        //建筑面积
        mViewBinding.etStructureArea.setText(entity.getStructure_area());
        //建筑年份
        mViewBinding.etBuildYear.setText(entity.getBuild_year());
        //现状楼牌号
        mViewBinding.etDoorNumber.setText(entity.getDoor_number());
        //登记时间
        try {
            mViewBinding.tvCheckinDate.setText(TimeUtils.millis2StringDay(Long.parseLong(entity.getCheckin_date()) * 1000));
        } catch (Exception e) {
            mViewBinding.tvCheckinDate.setText("");
        }
        //所在楼层
        mViewBinding.etFloorNumber.setText(entity.getFloor_number());
        //楼层总数
        mViewBinding.etAllFloor.setText(entity.getAll_floor());
        //唯一房产
        if ("0".equals(entity.getIs_only_house())) {
            mViewBinding.expandableLayout.expand();
            //其他房产
            if (!StringUtils.isEmpty(entity.getOther_house_amount())) {
                mViewBinding.etOtherHouseAmount.setText(entity.getOther_house_amount());
            }
        } else {
            mViewBinding.expandableLayout.collapse();
            mRequest.setOther_house_amount("");
            mOldRequest.setOther_house_amount("");
        }
        //下拉框字段
        TuftInfoEntity.ChooseListBean bean = entity.getChoose_list();
        mViewBinding.tvRingRdDirection.setText(bean.getRing_rd_direction() + bean.getCircle_position());
        mViewBinding.tvRoomConstruction.setText(bean.getRoom_construction());
        mViewBinding.tvHouseUse.setText(bean.getHouse_use());
        //产权类型
        mViewBinding.tvPropertyRightType.setText(bean.getProperty_right_type());
        //房屋朝向
        mViewBinding.tvHourseOrientation.setText(bean.getHourse_orientation());
        //装修状况
        mViewBinding.tvFitmentStatus.setText(bean.getFitment_status());
        //建筑类型
        mViewBinding.tvStructureType.setText(bean.getStructure_type());
        //使用状态
        mViewBinding.tvUseinStatue.setText(bean.getUsein_statue());
        //整体结构
        mViewBinding.tvStructureModify.setText(bean.getStructure_modify());
        //唯一房产
        mViewBinding.tvIsOnlyHouse.setText(bean.getIs_only_house());
        //购买年数
        mViewBinding.tvPurchaseYear.setText(bean.getPurchase_year());
    }

    /**
     * 环路区间
     *
     * @param list
     */
    @Override
    public void returnRingRdDirectionData(List<PickerEntity> list) {
        mRingRdDirectionData = list;
    }

    /**
     * 房屋结构
     *
     * @param list
     */
    @Override
    public void returnRoomConstructionData(List<PickerEntity> list) {
        PickerViewHelper.showOnePickerView(_mActivity, "房屋结构", mRequest.getRoom_construction(), list, pickerEntity1 -> {
            String room_construction = pickerEntity1.getSign_id();
            mRequest.setRoom_construction(room_construction);
            mViewBinding.tvRoomConstruction.setText(pickerEntity1.getTitle());
        });
    }

    /**
     * 环路区间环数
     *
     * @param list
     * @return list
     */
    @Override
    public void returnCirclePositionData(List<PickerEntity> list) {
        mCirclePositionData = list;
        PickerViewHelper.showTwoPickerView(_mActivity, "环路区间", mRequest.getRing_rd_direction(), mRequest.getCircle_position(),
                mRingRdDirectionData, mCirclePositionData, (pickerEntity1, pickerEntity2) -> {
                    String ring_rd_direction = pickerEntity1.getSign_id();
                    String circle_position = pickerEntity2.getSign_id();
                    mRequest.setRing_rd_direction(ring_rd_direction);
                    mRequest.setCircle_position(circle_position);
                    mViewBinding.tvRingRdDirection.setText(pickerEntity1.getTitle() + pickerEntity2.getTitle());
                });
    }

    /**
     * 房屋用途
     *
     * @param list
     * @return list
     */
    @Override
    public void returnHouseUseData(List<PickerEntity> list) {
        PickerViewHelper.showOnePickerView(_mActivity, "房屋用途", mRequest.getHouse_use(), list, pickerEntity1 -> {
            String house_use = pickerEntity1.getSign_id();
            mRequest.setHouse_use(house_use);
            mViewBinding.tvHouseUse.setText(pickerEntity1.getTitle());
        });
    }

    /**
     * 产权类型
     *
     * @param list
     * @return list
     */
    @Override
    public void returnPropertyRightTypeData(List<PickerEntity> list) {
        PickerViewHelper.showOnePickerView(_mActivity, "产权类型", mRequest.getProperty_right_type(), list, pickerEntity1 -> {
            String property_right_type = pickerEntity1.getSign_id();
            mRequest.setProperty_right_type(property_right_type);
            mViewBinding.tvPropertyRightType.setText(pickerEntity1.getTitle());
        });
    }

    /**
     * 房屋朝向
     *
     * @param list
     * @return list
     */
    @Override
    public void returnHourseOrientationData(List<PickerEntity> list) {
        PickerViewHelper.showOnePickerView(_mActivity, "房屋朝向", mRequest.getHourse_orientation(), list, pickerEntity1 -> {
            String hourse_orientation = pickerEntity1.getSign_id();
            mRequest.setHourse_orientation(hourse_orientation);
            mViewBinding.tvHourseOrientation.setText(pickerEntity1.getTitle());
        });
    }

    /**
     * 装修状况
     *
     * @param list
     * @return list
     */
    @Override
    public void returnFitmentStatusData(List<PickerEntity> list) {
        PickerViewHelper.showOnePickerView(_mActivity, "装修状况", mRequest.getFitment_status(), list, pickerEntity1 -> {
            String fitment_status = pickerEntity1.getSign_id();
            mRequest.setFitment_status(fitment_status);
            mViewBinding.tvFitmentStatus.setText(pickerEntity1.getTitle());
        });
    }

    /**
     * 建筑类型
     *
     * @param list
     * @return list
     */
    @Override
    public void returnStructureTypeData(List<PickerEntity> list) {
        PickerViewHelper.showOnePickerView(_mActivity, "建筑类型", mRequest.getStructure_type(), list, pickerEntity1 -> {
            String structure_type = pickerEntity1.getSign_id();
            mRequest.setStructure_type(structure_type);
            mViewBinding.tvStructureType.setText(pickerEntity1.getTitle());
        });
    }

    /**
     * 使用状态
     *
     * @param list
     * @return list
     */
    @Override
    public void returnUseinStatueData(List<PickerEntity> list) {
        PickerViewHelper.showOnePickerView(_mActivity, "使用状态", mRequest.getUsein_statue(), list, pickerEntity1 -> {
            String usein_statue = pickerEntity1.getSign_id();
            mRequest.setUsein_statue(usein_statue);
            mViewBinding.tvUseinStatue.setText(pickerEntity1.getTitle());
        });
    }

    /**
     * 整体结构
     *
     * @param list
     * @return list
     */
    @Override
    public void returnStructureModifyData(List<PickerEntity> list) {
        PickerViewHelper.showOnePickerView(_mActivity, "整体结构", mRequest.getStructure_modify(), list, new PickerViewHelper.OnOneSelectListener() {
            @Override
            public void OnOneSelect(PickerEntity pickerEntity1) {
                String structure_modify = pickerEntity1.getSign_id();
                mRequest.setStructure_modify(structure_modify);
                mViewBinding.tvStructureModify.setText(pickerEntity1.getTitle());
            }
        });
    }

    /**
     * 唯一房产
     *
     * @param list
     * @return list
     */
    @Override
    public void returnIsOnlyHouseData(List<PickerEntity> list) {
        PickerViewHelper.showOnePickerView(_mActivity, "唯一房产", mRequest.getIs_only_house(), list, pickerEntity1 -> {
            String is_only_house = pickerEntity1.getSign_id();
            mRequest.setIs_only_house(is_only_house);
            mViewBinding.tvIsOnlyHouse.setText(pickerEntity1.getTitle());
            if ("0".equals(mRequest.getIs_only_house())) {
                mViewBinding.expandableLayout.expand();
            } else {
                mViewBinding.expandableLayout.collapse();
            }
        });
    }

    /**
     * 购买年数
     *
     * @param list
     * @return list
     */
    @Override
    public void returnPurchaseYearData(List<PickerEntity> list) {
        PickerViewHelper.showOnePickerView(_mActivity, "购买年数", mRequest.getPurchase_year(), list, pickerEntity1 -> {
            String purchase_year = pickerEntity1.getSign_id();
            mRequest.setPurchase_year(purchase_year);
            mViewBinding.tvPurchaseYear.setText(pickerEntity1.getTitle());
        });
    }

    /**
     * 房屋户型
     *
     * @param room_amount
     * @param hall_amount
     * @param kitchen_amount
     * @param toilet_amount
     */
    private void setAmount(String room_amount, String hall_amount, String toilet_amount, String kitchen_amount) {
        mRequest.setRoom_amount(room_amount);
        mRequest.setHall_amount(hall_amount);
        mRequest.setToilet_amount(toilet_amount);
        mRequest.setKitchen_amount(kitchen_amount);
        mViewBinding.tvAmount.setText(mRequest.getRoom_amount() + "室" +
                mRequest.getHall_amount() + "厅" +
                mRequest.getToilet_amount() + "卫" + mRequest.getKitchen_amount() + "厨");
    }

    public class ClickHandler {
        public void onShowAmountPickerView(View view) {
            PickerViewHelper.showAmountpinion(_mActivity, mRequest.getRoom_amount(),
                    mRequest.getHall_amount(), mRequest.getToilet_amount(), mRequest.getKitchen_amount(),
                    (room, hall, toilet, kitchen) -> setAmount(room, hall, toilet, kitchen));
        }

        public void onShowCirclePositionPickerView(View view) {
            mPresenter.loadRingRdDirectionData();
        }

        public void onShowRoomConstructionPickerView(View view) {
            mPresenter.loadRoomConstructionData();
        }

        public void onShowHouseUsePickerView(View view) {
            mPresenter.loadHouseUseData();
        }

        public void onShowPropertyRightTypePickerView(View view) {
            mPresenter.loadPropertyRightTypeData();
        }

        public void onShowHourseOrientationPickerView(View view) {
            mPresenter.loadHourseOrientationData();
        }

        public void onShowFitmentStatusPickerView(View view) {
            mPresenter.loadFitmentStatusData();
        }

        public void onShowStructureTypePickerView(View view) {
            mPresenter.loadStructureTypeData();
        }

        public void onShowUseinStatuePickerView(View view) {
            mPresenter.loadUseinStatueData();
        }

        public void onShowStructureModifyPickerView(View view) {
            mPresenter.loadStructureModifyData();
        }

        public void onShowIsOnlyHousePickerView(View view) {
            mPresenter.loadIsOnlyHouseData();
        }

        public void onShowPurchaseYearPickerView(View view) {
            mPresenter.loadPurchaseYearData();
        }

        //等级时间
        public void onShowCheckinDatePickerView(View view) {
            Calendar startDate = Calendar.getInstance();
            startDate.set(1955, 0, 1);
            Calendar endData = Calendar.getInstance();//系统当前时间
            Calendar selectData = Calendar.getInstance();
            if (!StringUtils.isEmpty(mRequest.getCheckin_date())) {
                selectData.setTime(TimeUtils.millis2Date(Long.parseLong(mRequest.getCheckin_date()) * 1000));
            }
            PickerViewHelper.showYearMonthDayPicker(_mActivity, "登记时间", startDate, endData, selectData, date -> {
                String date2String = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()));
                mViewBinding.tvCheckinDate.setText(date2String);
                String checkin_date = String.valueOf(TimeUtils.string2Millis(date2String, new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())) / 1000);
                mRequest.setCheckin_date(checkin_date);
            });
        }

        public void onSave(View view) {
            saveData();
        }

    }

    public void saveData() {
        setSaveData();
        if (mRequest.toString().equals(mOldRequest.toString())) {
            ToastUtils.showLong("您没有更改任何信息，无需保存");
            return;
        }
        isNetSuccess = false;
        mPresenter.saveTuftInfo(mRequest);
    }

    public boolean isSaveData() {
        //如果请求错误则返回true
        if (!isNetSuccess) {
            return true;
        }
        setSaveData();
        if (mRequest.toString().equals(mOldRequest.toString())) {
            return true;
        } else {
            return false;
        }
    }

    private void setSaveData() {
        mRequest.setProperty_owner(mViewBinding.etPropertyOwner.getText().toString().trim());
        mRequest.setHouse_located(mViewBinding.etHouseLocated.getText().toString().trim());
        mRequest.setCommunity_name(mViewBinding.etCommunityName.getText().toString().trim());
        mRequest.setCertificate_number(mViewBinding.etCertificateNumber.getText().toString().trim());
        mRequest.setStructure_area(mViewBinding.etStructureArea.getText().toString().trim());
        mRequest.setBuild_year(mViewBinding.etBuildYear.getText().toString().trim());
        mRequest.setDoor_number(mViewBinding.etDoorNumber.getText().toString().trim());
        mRequest.setFloor_number(mViewBinding.etFloorNumber.getText().toString().trim());
        mRequest.setAll_floor(mViewBinding.etAllFloor.getText().toString().trim());
        if ("0".equals(mRequest.getIs_only_house())) {
            mRequest.setOther_house_amount(mViewBinding.etOtherHouseAmount.getText().toString().trim());
        } else {
            mRequest.setOther_house_amount("");
        }
    }
}
